package com.zmh.service.httpclient;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zmh.common.FileUtil;
import com.zmh.model.httpclient.HttpHeader;

/** 
 * @author zhoumh
 * @version 创建时间：2017年12月7日 下午3:23:51 
 * @Description 
*/
@Service
public class ChehuoGif {
	private static Logger logger = LoggerFactory.getLogger(ChehuoGif.class);

	@Autowired
	private HttpConnectionManager httpConnectionManager;
	private static CloseableHttpClient httpClient = null;
	private static CloseableHttpResponse response = null;
	private static Header[] headers = null ;
	private static HttpClientContext httpContext = HttpClientContext.create();;
	@PostConstruct
	public void init() {
		getHttpClient();
	}
	@PreDestroy
	public void dostory() {
		closeHttpClient();
	}
	
	public void getGifByWX(){
		
	}
	
	/**
	 * 从搞笑gif上下载车祸动图
	 *  
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2017年12月9日 下午4:25:24 
	 * @Description:
	 */
	public void getGifByGX(){
		headers = HttpHeader.custom()
				.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36")
				.build();
		for(int i = 1;i<20;i++){
			String url = "http://www.gaoxiaogif.com/tag/chehuoGIF/";
			if (i>1) {
				url = url+"index_"+i+".html";
			}
			System.out.println(url);
			String html = getHTML(url);
			Document doc = Jsoup.parse(html);
			Elements es = doc.getElementsByAttribute("gifsrc");
			for (Element el : es) {
				String gifsrc = el.attr("gifsrc");
				String name = el.attr("alt");
				System.out.println(gifsrc+"  "+name);
				getImg(gifsrc,name);
			}
		}
	}
	
	/** 
     * 保存图片 
     * @param url
     * @throws Exception 
     * @return: void
     * @author: zhoumh
     * @version: 创建时间：2017年10月20日 下午5:32:38 
     * @Description: 可以尝试直接从URL获取文件流保存，并不需要通过httpclient
     */
	private boolean getImg(String url,String name) {  
		boolean result = false;
        String filePath = FileUtil.getStaticPath()+"/src/main/webapp/static/images/chehuo/"+name+".gif";
//        String filePath = FileUtil.getSysPath()+"/static/images/" + "qrcode.jpg";
        FileUtil.deleteFile(filePath);
        BufferedOutputStream out = null;  
        //获取登陆认证二维码的字节流
        byte[] bit = getByte(url);  
        if (bit.length > 0) {  
            try {  
                out = new BufferedOutputStream(new FileOutputStream(filePath));  
                out.write(bit);  
                out.flush();  
                result = true;
                logger.info("Create File success! [" + filePath + "]");  
            }catch (Exception e) {
            	 e.printStackTrace();  
            } finally {  
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}  
            }
        }
        return result;
    }  
	/**
     * 获取图片字节流  
     * @param uri
     * @throws Exception 
     * @return: byte[]
     * @author: zhoumh
     * @version: 创建时间：2017年10月20日 下午5:32:29 
     * @Description:
     */
    private byte[] getByte(String url) {  
    	try {
    		response = doGet(url);
    		HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {  
                if (entity != null) {  
                    return EntityUtils.toByteArray(entity);  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return new byte[0];  
    } 
    
	/**
	 * 根据URL发起请求并返回请求结果
	 * @param url 请求链接
	 * @author zhoumh
	 * @version 创建时间：2017年10月13日 上午10:30:47
	 */
	private String getHTML(String url) {
		String html = "";
		try {
			response = doGet(url);
			HttpEntity entity = response.getEntity();
			// 判断返回实体是否为空
			if (entity != null) {
				// 获取返回的内容
				html = EntityUtils.toString(entity, "GBK");
//				logger.info(html);
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return html;
	}
	
	/**
	 * 根据传入的URL和httpclient发起get请求并返回结果
	 * 
	 * @param url   请求的地址
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @return: CloseableHttpResponse
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月17日 上午11:04:45
	 * @Description:
	 */
	private CloseableHttpResponse doGet(String url)
			throws ClientProtocolException, IOException {
		HttpGet httpGet = new HttpGet(url);
		// 配置请求的HEADER部分 
		httpGet.setHeaders(headers);
		// 接收返回信息
		response = getHttpClient().execute(httpGet, httpContext);
		return response;
	}
	/**
	 * 根据传入的URL和httpclient发起POST请求并返回结果
	 * 
	 * @param url  请求的地址
	 * @param uefEntity 请求的表单
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @return: CloseableHttpResponse
	 * @author: zhoumh
	 * @version: 创建时间：2017年7月26日 下午5:19:23
	 * @Description:
	 */
	private CloseableHttpResponse doPost(String url,
			UrlEncodedFormEntity uefEntity)
			throws ClientProtocolException, IOException {
		// Post请求
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(uefEntity);
		//这个必须设置 否则无法登录
		httppost.setHeaders(headers);
		// 发送请求并接收返回信息
		response = getHttpClient().execute(httppost, httpContext);
		return response;
	}
	/**
	 * 循环输出所有cookie信息
	 *  
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月23日 上午10:21:00 
	 * @Description:
	 */
	private void getCookies(){
		httpContext.getCookieStore().getCookies().forEach(System.out::println);
	}
	/**
	 * 从连接池获取httpclient
	 * 
	 * @return: CloseableHttpClient
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月17日 上午9:45:28
	 * @Description:
	 */
	private CloseableHttpClient getHttpClient() {
		if (httpClient == null) {
			httpClient = httpConnectionManager.getHttpsClient();
			// 设置cookie
//			RequestConfig requestConfig = RequestConfig.custom()
//					.setConnectionRequestTimeout(10000)
//					.setConnectTimeout(10000)
//					.setCookieSpec(CookieSpecs.STANDARD_STRICT)
//					.build();
//			httpClient = HttpClients.custom()
//					.setDefaultRequestConfig(requestConfig)
//					.build();
		}
		return httpClient;
	}
	/**
	 * 关闭httpclient
	 * 
	 * @return: void
	 * @author: zhoumh
	 * @version: 创建时间：2017年10月17日 上午9:45:50
	 * @Description:
	 */
	private void closeHttpClient() {
		try {
			if (response != null) {
				response.close();
			}
			if (httpClient != null) {
				httpClient.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
